package com.ht.interfaces.controller;


import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ht.api.db.bean.AjaxResult;
import com.ht.api.db.util.HtUtil;
import com.ht.api.db.util.RedisUtil;
import com.ht.interfaces.service.LinkService;
import com.ht.interfaces.utils.AESEncrypter;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.view.RedirectView;
import java.util.Properties;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
public class LinkController {

    @GetMapping("/l/{state}")
    public RedirectView doLink(HttpServletRequest request,
                               @PathVariable String state,
                               @RequestHeader("Host") String host,
                               @RequestHeader(value = "openid", required = false) String openid,
                               @RequestParam(required = false) String tmpOpenid,
                               @RequestParam(required = false) String code) {

        if (StrUtil.isNotBlank(tmpOpenid)) {// 如果有传临时openid，则直接使用临时openid
            openid = tmpOpenid;
        }

        JSONObject link = LinkService.getLink(host, state);

        // 判断openid和授权code是否都为空，如果都为空则走授权逻辑
        if (StrUtil.isBlank(openid) && StrUtil.isBlank(code)) {
            String url = LinkService.doAuthorizeUrl(host, link);
            RedirectView redirectView = new RedirectView();
            redirectView.setUrl(url); // 目标URL

            // 直接重定向去授权
            return redirectView;

        } else if (StrUtil.isBlank(openid) && StrUtil.isNotBlank(code)) {
            openid = LinkService.analysisOpenid(link.getStr("appid"), code); // 解析openid
        }

        // 获取用户客户端信息
        JSONObject client = LinkService.buildClientInfo(request);
        LinkService.saveClickLog(host, openid, client, link);

        // 获取关联内容
        JSONObject result = LinkService.getContent(host, link, openid);

        return buildRedirectView(host, link.getStr("relation_type"), result);
    }

    @GetMapping("/token")
    public AjaxResult getTokenData(@RequestParam String token) {

        // 读取前端信息
        String info = RedisUtil.get(token);

        return AjaxResult.success("ok", info);
    }

    // 根据关联类型路由到具体页面，以及加密结果信息
    private RedirectView buildRedirectView (String host, String relationType, JSONObject result) {
        String url = "";
        if (relationType.equals("writings")) {
            url = "http://m.htiannet.com/h5/pagesCms/articleInfo/articleInfo";
        } else if (relationType.equals("questionnaire")) {
            url = "http://m.htiannet.com/h5/pages/questionnaire/questionnaire";
        }

        RedirectView redirectView = new RedirectView();
        String serialList = AESEncrypter.encrypt(result.toString(), "52413429751f7a7f");

        String token = "h5token" + HtUtil.getId();

        // 设置前端信息
        RedisUtil.set(token, serialList, 600, TimeUnit.SECONDS);

        redirectView.setUrl(url); // 目标URL
        Properties attributes = new Properties();
        attributes.put("host", host);
        attributes.put("token", token);
        redirectView.setAttributes(attributes);

        return redirectView;
    }



}
